package com.example.myapplication.model.https;

import android.support.annotation.NonNull;

import com.example.myapplication.model.rx.isThrowable;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.schedulers.IoScheduler;
import retrofit2.Call;

/**
 * Created by meishiyiyun on 2017/4/25.
 */

public class RxCallback<T> {
    public static <T> Flowable<T> create(@NonNull final Call<T> call) {
        return Flowable.create(e -> call.enqueue(new isThrowable<T>() {
            @Override
            protected void _onNext(T t) {
                e.onNext(t);
                e.onComplete();
                call.cancel();
            }

            @Override
            protected void _onError() {
                e.onComplete();
                call.cancel();
            }
        }), BackpressureStrategy.BUFFER);
    }

    /**
     * 后台线程执行同步，主线程执行异步操作
     * 并且拦截所有错误，不让app崩溃
     *
     * @param <T> 数据类型
     * @return Transformer
     */
    public static <T> FlowableTransformer<T, T> background() {
        return upstream -> upstream.subscribeOn(new IoScheduler())
                .observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext(Flowable.<T>empty());
    }

}
